package com.card.service.system;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

/**
 * ClassName: SmsService <br/>
 * Function: 短信服务. <br/>
 * date: 2018年10月18日 下午6:00:20 <br/>
 * 
 * @author lishuai8
 * @version
 * @since JDK 1.8
 */
@Service("smsService")
public class SmsService {

	private static final Logger logger = LoggerFactory.getLogger(SmsService.class);

	@Value("${sms.api}")
	private String smsApi;

	@Value("${sms.tempid}")
	private int tempId;

	@Value("${sms.signid}")
	private int signid;

	@Value("${sms.auth}")
	private String auth;

	public boolean sendSms(String mobile, String code) {
		// 短信发送状态
		boolean state = false;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		try {
			HttpPost httpPost = new HttpPost(smsApi);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("mobile", mobile);
			jsonObject.put("sign_id", signid);
			jsonObject.put("temp_id", tempId);
			JSONObject tempPara = new JSONObject();
			tempPara.put("code", code);
			jsonObject.put("temp_para", tempPara);
			httpPost.setHeader("Content-Type", "application/json");
			httpPost.setHeader("Authorization", auth);
			httpPost.setEntity(new StringEntity(jsonObject.toJSONString(), "utf-8"));
			logger.info("============================开始发送短信");
			response = httpClient.execute(httpPost);
			logger.info("============================发送完成：response" + response.getEntity().toString());
			entity = response.getEntity();
			if (resultUtils(EntityUtils.toString(entity))) {
				state = true;
			} else {
				state = false;
				logger.error("短信推送失败response:{}", response);
			}
		} catch (IOException e) {
			logger.error("sendSms() IO exception: {}", e);
		} finally {
			if (entity != null) {
				try {
					EntityUtils.consume(entity);
				} catch (IOException e) {
					logger.error("sendSms() IOException:", e);
				}
			}
		}
		return state;
	}

	private boolean resultUtils(String result) {
		JSONObject object = JSONObject.parseObject(result);
		if (object.get("error") == null) {
			return true;
		} else {
			return false;
		}
	}
}
